package com.xiaoma.h5testdemo.common.base

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.xiaoma.common.ui.BaseFragment

/**
 * author: liangjingbo
 * date: 2023/11/30
 * describe:
 */
abstract class BaseSupportFrgBackFragment<VB : ViewBinding>(
    inflate: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : BaseFragment<VB>(inflate) {

    override fun onBackPressed(): Boolean {
        return handleFragmentBackPress()
    }
    private fun handleFragmentBackPress(): Boolean {
        val fragments: List<Fragment> = childFragmentManager.fragments
        for (i in fragments.indices.reversed()) {
            val child: Fragment = fragments[i]
            if (child is BaseFragment<*>) {
                if (isFragmentBackHandled(child)) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * 判断Fragment是否处理了Back键
     *
     * @return 如果处理了back键则返回 **true**
     */
    private fun isFragmentBackHandled(fragment: BaseFragment<*>): Boolean {
        if (!fragment.isVisible || !fragment.isResumed) { //在本工程不管是viewpager还是show、hide都只需要判断onResume即可
            return false
        }
        return fragment.onBackPressed()
    }
}